package org.shop.controller.app;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.shop.entity.Attention;
import org.shop.entity.Favorites;
import org.shop.entity.Goods;
import org.shop.entity.GoodsClassify;
import org.shop.entity.Merchant;
import org.shop.entity.ShoppingTrolley;
import org.shop.entity.security.MyUserDetail;
import org.shop.service.AttentionService;
import org.shop.service.FavoritesService;
import org.shop.service.GoodsAppraisesService;
import org.shop.service.GoodsClassifyService;
import org.shop.service.GoodsService;
import org.shop.service.LeaveMessageService;
import org.shop.service.MerchantService;
import org.shop.service.ShoppingCardService;
import org.shop.util.CommonUtil;
import org.shop.util.DateUtils;
import org.shop.util.FtpUtil2;
import org.shop.util.ObjUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


@Controller
public class GoodsController {
    private static Logger logger = LogManager.getLogger(GoodsController.class);

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private FavoritesService favoritesService;
    @Autowired
    private LeaveMessageService leaveMessageService;
    @Autowired
    private AttentionService attentionService;
    @Autowired
    private GoodsAppraisesService goodsAppraisesService;
	@Autowired
    private ShoppingCardService shoppingTrolleyService;
	@Autowired
	private MerchantService merchantService;

    /**
     * 获取商品信息并进入商品列表界面
     * @param req goodsName(商品名) merchantId(商家ID)
     * @return
     */
//    @RequestMapping("app/goodsList")
//    public String goodsList(HttpServletRequest req){
//        String goodsName = req.getParameter("goodsName");
//        String merchantId = req.getParameter("merchantId");
//        String goodsIdentifying = req.getParameter("goodsIdentifying");
//        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
//        List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
//        //获取登录人用户信息
//        SecurityContextImpl securityContextImpl = (SecurityContextImpl)req.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
//        MyUserDetail ud = null;
//        if(ObjUtil.isNotNullAndEmpty(securityContextImpl)) {
//        	ud = (MyUserDetail) securityContextImpl.getAuthentication().getPrincipal();
//        }
//        try {
//            Map<String, Object> paramMap = new HashMap<String, Object>();
//            paramMap.put("goodsName", goodsName);
////            paramMap.put("schoolId", ud.getSchoolId());
//            paramMap.put("schoolId", (long)1);
//            if(ObjUtil.isNotNullAndEmpty(merchantId)) {
//            	paramMap.put("merchantId", Long.parseLong(merchantId));
//            }
//            if(ObjUtil.isNotNullAndEmpty(goodsIdentifying)) {
//            	paramMap.put("goodsIdentifying", Long.parseLong(goodsIdentifying));
//            }
//            list = goodsService.getGoodsList(paramMap);
//        	for(int i=0;i<list.size();i++) {
//        		Map<String, Object> m = new HashMap<String, Object>();
//        		m = list.get(i);
//        		if(ObjUtil.isNotNullAndEmpty(ud)) {
//        			Map<String, Object> params = new HashMap<String, Object>();
//        			params.put("goodsId", m.get("goodsId"));
//                    params.put("userId", ud.getUserId());
//                    ShoppingTrolley shoppingCard = shoppingTrolleyService.getShoppingCardGoods(params);
//                    if(ObjUtil.isNotNullAndEmpty(shoppingCard)) {
//                    	m.put("goodsCount", shoppingCard.getOrderCount());
//                    }
//                }
//        		list2.add(m);
//        	}
//        	req.setAttribute("goodsList", list2);
//            Attention attention = new Attention();
//            if(ObjUtil.isNotNullAndEmpty(ud)) {
//                attention.setUserId(ud.getUserId());
//                List<Attention> attentionList = attentionService.getAtternionList(attention);//查询改店铺是否被我关注
//                req.setAttribute("attentionList", attentionList);
//            }
////            Attention att = new Attention();
////            att.setTargetId(Long.parseLong(merchantId));
////            att.setAttentionType((byte)1);
////            List<Attention> attentionSize = attentionService.getAtternionList(att);//查询该店铺被被关注的数量
////            req.setAttribute("attentionSize", attentionSize.size());
//            
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(e);
//        }
//        return "app/goodsList";
//    }
    /**
     * 获取商品信息并进入商品列表界面
     * @param req goodsName(商品名) merchantId(商家ID)
     * @return
     */
    @RequestMapping("app/goodsList")
    public String goodsList(HttpServletRequest req){
    	String goodsName = req.getParameter("goodsName");
    	String merchantId = req.getParameter("merchantId");
    	String goodsIdentifying = req.getParameter("goodsIdentifying");
    	List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    	List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
    	//获取登录人用户信息
    	SecurityContextImpl securityContextImpl = (SecurityContextImpl)req.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
    	MyUserDetail ud = null;
    	if(ObjUtil.isNotNullAndEmpty(securityContextImpl)) {
    		ud = (MyUserDetail) securityContextImpl.getAuthentication().getPrincipal();
    	}
    	try {
    		Map<String, Object> paramMap = new HashMap<String, Object>();
    		paramMap.put("goodsName", goodsName);
    		paramMap.put("schoolId", (long)1);
    		if(ObjUtil.isNotNullAndEmpty(merchantId)) {
    			paramMap.put("merchantId", Long.parseLong(merchantId));
    		}
    		if(ObjUtil.isNotNullAndEmpty(goodsIdentifying)) {
    			paramMap.put("goodsIdentifying", Long.parseLong(goodsIdentifying));
    		}
    		
    		List<Map<String,Object>> goodsClassifyList = goodsService.getMerchantGoodsClassifyList(paramMap);//获取所有类别
    		List<Map<String, Object>> goodsClassifyList2 = new ArrayList<Map<String, Object>>();
    		if(goodsClassifyList.size() > 0) {
    			for(int i=0;i<goodsClassifyList.size();i++) {
    				Map<String, Object> map = goodsClassifyList.get(i);
    				paramMap.put("classifyId1", map.get("cassifyId"));
    				List<Map<String, Object>> goodsList = goodsService.getGoodsList(paramMap);//获取该类别的所有商品
    				List<Map<String, Object>> goodsList2 = new ArrayList<Map<String, Object>>();
    				for(int j=0;j<goodsList.size();j++) {
    	    			Map<String, Object> m = new HashMap<String, Object>();
    	    			m = goodsList.get(j);
    	    			if(ObjUtil.isNotNullAndEmpty(ud)) {
    	    				Map<String, Object> params = new HashMap<String, Object>();
    	    				params.put("goodsId", m.get("goodsId"));
    	    				params.put("userId", ud.getUserId());
    	    				ShoppingTrolley shoppingCard = shoppingTrolleyService.getShoppingCardGoods(params);
    	    				if(ObjUtil.isNotNullAndEmpty(shoppingCard)) {
    	    					m.put("goodsCount", shoppingCard.getOrderCount());
    	    				}
    	    			}
    	    			goodsList2.add(m);
    	    			
    	    		}
    				map.put("goodsList", goodsList2);
    				goodsClassifyList2.add(map);
    			}
    		}
    		
    		req.setAttribute("goodsClassifyList", goodsClassifyList2);
    		//获取店铺信息
    		if(ObjUtil.isNotNullAndEmpty(merchantId)) {
    			Merchant merchant = merchantService.selectByPrimaryKey(Long.parseLong(merchantId));
    			req.setAttribute("merchant", merchant);
    		}
    		//获取对该店铺的所有评论
    		List<Map<String, Object>> merchantAppraisesList = goodsAppraisesService.getMerchantAppraisesList(paramMap);
    		req.setAttribute("merchantAppraisesList", merchantAppraisesList);
    		//查询该店铺是否被我关注
    		Attention attention = new Attention();
    		if(ObjUtil.isNotNullAndEmpty(ud)) {
    			attention.setUserId(ud.getUserId());
    			List<Attention> attentionList = attentionService.getAtternionList(attention);//查询该店铺是否被我关注
    			req.setAttribute("attentionList", attentionList);
    		}
//            Attention att = new Attention();
//            att.setTargetId(Long.parseLong(merchantId));
//            att.setAttentionType((byte)1);
//            List<Attention> attentionSize = attentionService.getAtternionList(att);//查询该店铺被被关注的数量
//            req.setAttribute("attentionSize", attentionSize.size());
    		
    	} catch (Exception e) {
    		e.printStackTrace();
    		logger.error(e);
    	}
    	return "app/goodsList";
    }

    
    /**
     * 获取我发布的 所有商品列表(个人)
     * @param req
     * @return
     */
//    @RequestMapping("app/getUserGoodsList")
//    @ResponseBody
//    public List<Goods> getUserGoodsList(HttpServletRequest req){
//        List<Goods> list = new ArrayList<Goods>();
//        //获取登录人用户信息
//        MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        try {
//            Map<String, Object> paramMap = new HashMap<String, Object>();
//            paramMap.put("userId", ud.getUserId());
//            paramMap.put("used", 2);
//            list = goodsService.getUserGoodsList(paramMap);
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(e);
//        }
//        return list;
//    }

    /**
     * 获取店铺商品列表
     * @param req
     * @return
     */
//    @RequestMapping("app/getGoodsList")
//    @ResponseBody
//    public List<Map<String, Object>> getGoodsList(HttpServletRequest req){
//        String goodsName = req.getParameter("goodsName");
//        String merchantId = req.getParameter("merchantId");
//        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
//        //获取登录人用户信息
//        MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        try {
//            Map<String, Object> paramMap = new HashMap<String, Object>();
//            paramMap.put("goodsName", goodsName);
//            paramMap.put("schoolId", ud.getSchoolId());
//            paramMap.put("merchantId", Long.parseLong(merchantId));
//            list = goodsService.getGoodsList(paramMap);
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(e);
//        }
//        return list;
//    }

    
    /**
     * app通过商品ID获取商品信息
     * @param req
     * @return
     */
    @RequestMapping("app/getAppGoodsInfo")
    @ResponseBody
    public Goods getAppGoodsInfo(HttpServletRequest req){
    	String goodsId = req.getParameter("goodsId");
    	Goods goodsInfo = null;
    	try {
    		goodsInfo = goodsService.selectByPrimaryKey(Long.parseLong(goodsId));
    	} catch (Exception e) {
    		e.printStackTrace();
    		logger.error(e);
    	}
    	return goodsInfo;
    }
    
    
    /**
     * 商品删除
     * @param req
     * @return
     */
    @RequestMapping("app/delGoods")
    @ResponseBody
    public Map<String, Object> delGoods(HttpServletRequest req){
        Map<String, Object> map=new HashMap<String, Object>();
        String goodsId = req.getParameter("goodsId");
        try {
            goodsService.deleteByPrimaryKey(Long.parseLong(goodsId));
            map.put("state", 1);
            map.put("msg", "删除成功");
        } catch(Exception e) {
            map.put("state", 0);
            map.put("msg", "删除失败");
            logger.error(e);
        }
        return map;
    }
    

    /**
     * @Title: toGoodsInfo
     * @Description: TODO(根据商品id跳转到商品详细信息)
     * @param @param req
     * @param @return
     * @return String    返回类型
     * @throws
     */
    @RequestMapping("app/toGoodsInfo")
    public String toGoodsInfo(HttpServletRequest req){
    	Map<String,Object> paramMap = new HashMap<String,Object>();
        //获取登录人用户信息
        MyUserDetail ud = null;
        if(ObjUtil.isNotNullAndEmpty(SecurityContextHolder.getContext().getAuthentication())) {
            ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        Long goodsId = Long.parseLong(req.getParameter("goodsId"));
        try{
            Goods goods = goodsService.selectByPrimaryKey(goodsId);
            req.setAttribute("goods", goods);
            paramMap.put("goodsId", goodsId);
            List<Map<String, Object>> aboutGoodsOfAppraises = goodsAppraisesService.getAboutGoodsOfAppraises(paramMap);
            req.setAttribute("aboutGoodsOfAppraises", aboutGoodsOfAppraises);
            int pageView = goods.getPageView();
            goods.setPageView(pageView+1);
            goodsService.updateByPrimaryKeySelective(goods);
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return "app/goodsInfo";
    }

    /**
     * @Title: getGoodsPhotoByName
     * @Description: TODO(通过照片路径获取照片)
     * @param @param req
     * @param @param res
     * @return void    返回类型
     * @throws
     */
    @RequestMapping("app/getGoodsPhotoByName")
    public void getGoodsPhotoByName(HttpServletRequest req,HttpServletResponse res){
        String photoStr=req.getParameter("goodsImage");
        OutputStream os =null;
        InputStream is =null;
        FTPClient ftpClient =null;
        try {
            res.setContentType("shop/image");
            ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"));
            if(photoStr.lastIndexOf("/")>0){
                FtpUtil2.changeWorkingDirectory(photoStr.substring(0, photoStr.lastIndexOf("/")), ftpClient);
                is=FtpUtil2.retrieveFileStream(photoStr.substring(photoStr.lastIndexOf("/")+1,photoStr.length()), ftpClient);
            }else{
                is=FtpUtil2.retrieveFileStream(photoStr, ftpClient);
            }
            os=res.getOutputStream();
            byte[] buf = new byte[1024];
            while (true) {
                int read = 0;
                if (is != null) {
                    read = is.read(buf);
                }
                if (read == -1) {
                    break;
                }
                os.write(buf, 0, read);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                if(os != null) {
                    os.close();
                }
            } catch (IOException e) {
                os=null;
            }
            try {
                if(is != null) {
                    is.close();
                }
            } catch (IOException e) {
                is=null;
            }
        }
    }



    /**
     * 获取商品图片
     * @param req
     * @return
     */
    @RequestMapping("app/getGoodsPhoto")
    public void getGoodsPhoto(HttpServletRequest req,HttpServletResponse res){
        String photoStr=req.getParameter("photoUrl");
        OutputStream os =null;
        InputStream is =null;
        FTPClient ftpClient =null;
        try {
            res.setContentType("image/jpg");
            ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"));
            if(photoStr.lastIndexOf("/")>0){
                FtpUtil2.changeWorkingDirectory(photoStr.substring(0, photoStr.lastIndexOf("/")), ftpClient);
                is=FtpUtil2.retrieveFileStream(photoStr.substring(photoStr.lastIndexOf("/")+1,photoStr.length()), ftpClient);
            }else{
                is=FtpUtil2.retrieveFileStream(photoStr, ftpClient);
            }
            os=res.getOutputStream();
            byte[] buf = new byte[1024];
            while (true) {
                int read = 0;
                if (is != null) {
                    read = is.read(buf);
                }
                if (read == -1) {
                    break;
                }
                os.write(buf, 0, read);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
            try {
                os.close();
            } catch (IOException e) {
                os=null;
            }
            try {
                is.close();
            } catch (IOException e) {
                is=null;
            }
        }
    }

    /**
     * 上传图片
     * @param req
     * @return
     */
    @RequestMapping("app/uploadUsedImg")
    @ResponseBody
    public Map<String, Object> uploadUsedImg(HttpServletRequest req){
        Map<String, Object> map=new HashMap<String, Object>();
        String photoStr="";
        String mainPhotoStr="";
        FTPClient ftpClient =null;
        try{
            //创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getSession().getServletContext());
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req;
            //判断 request 是否有文件上传,即多部分请求
            if(multipartResolver.isMultipart(req)){
                //取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                //创建ftp链接
                String ftp_photoDirectory="shop/image/" + DateUtils.toYmdX(new Date());
                ftpClient=FtpUtil2.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
                while(iter.hasNext()){
                    String name=iter.next();
                    if(name.equals("goodsMainPhoto")){
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        InputStream is = file.getInputStream();
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        mainPhotoStr+=ftp_photoDirectory+"/"+myFileName;
                                    }
                                }
                            }
                        }
                    }else{
                        //取得上传文件
                        List<MultipartFile> fileList = multiRequest.getFiles(name);
                        if(fileList!=null){
                            for(MultipartFile file:fileList){
                                if(file != null){
                                    //取得当前上传文件的文件名称
                                    String myFileName = file.getOriginalFilename();
                                    myFileName=FtpUtil2.generateFileName(myFileName);
                                    //如果名称不为"",说明该文件存在，否则说明该文件不存在
                                    if(myFileName.trim() !=""){
                                        myFileName=FtpUtil2.generateFileName(myFileName);
                                        InputStream is = file.getInputStream();
                                        FtpUtil2.upload(myFileName, is, ftpClient);
                                        if("".equals(photoStr)){
                                            photoStr+=ftp_photoDirectory+"/"+myFileName;
                                        }else{
                                            photoStr+=","+ftp_photoDirectory+"/"+myFileName;;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                map.put("photoStr", photoStr);
                map.put("state", 1);
                map.put("msg", "上传成功");
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
            map.put("msg", "上传失败");
        }finally {
            try {
                if(ftpClient!=null){
                    FtpUtil2.closeConnection(ftpClient);
                }
            } catch (Exception e) {
                ftpClient=null;
            }
        }
        return map;
    }

    /**
     * 发布二手商品（个人）
     * @param req
     * @return
     */
    @RequestMapping("app/addUsedGoods")
    @ResponseBody
    public Map<String, Object> addUsedGoods(HttpServletRequest req){
        Map<String, Object> map=new HashMap<String, Object>();
        try{
            String goodsName = req.getParameter("goodsName");
            String goodsIntro = req.getParameter("goodsIntro");
            String goodsPrice = req.getParameter("goodsPrice");
            String goodsQuondamPrice = req.getParameter("goodsQuondamPrice");
            String classifyId1 = req.getParameter("classifyId1");
            String photoStr = req.getParameter("photoStr");
            String goodsIdentifying = req.getParameter("goodsIdentifying");
            String str=goodsName+goodsIntro;
            String textBlackList=CommonUtil.getPropertiesParam("textBlackList");
            for(String textBlack:textBlackList.split(",")){
                if(str.contains(textBlack)){
                    map.put("state", 2);
                    map.put("msg", "发布内容不合法");
                    return map;
                }
            }
            MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            Goods goods = new Goods();
            goods.setGoodsName(goodsName);
            goods.setGoodsIntro(goodsIntro);
            goods.setGoodsPrice(new BigDecimal(goodsPrice));
            goods.setGoodsQuondamPrice(new BigDecimal(goodsQuondamPrice));
            goods.setClassifyId1(Long.parseLong(classifyId1));
            goods.setGoodsImage(photoStr);
            String[] arr = photoStr.split(",");
            goods.setGoodsThums(arr[0]);
            goods.setUserId(ud.getUserId());
            goods.setState((byte)2);
            goods.setGoodsIdentifying(Byte.parseByte(goodsIdentifying));
            goodsService.insertSelective(goods);
            map.put("goodsId", goods.getGoodsId());
            map.put("state", 1);
            map.put("msg", "发布成功");
        }catch(Exception e){
            e.printStackTrace();
            logger.error(e);
            map.put("state", 0);
            map.put("msg", "发布失败");
        }
        return map;
    }


    /**
     * 获取二手商品列表
     * @param req
     * @return
     */
    @RequestMapping("app/getUsedGoodsList")
    public String getUsedGoodsList(HttpServletRequest req){
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> buyGoodsList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> buyGoodsList2 = new ArrayList<Map<String, Object>>();
        SecurityContextImpl securityContextImpl = (SecurityContextImpl)req.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        MyUserDetail ud = null;
        if(ObjUtil.isNotNullAndEmpty(securityContextImpl)) {
        	ud = (MyUserDetail) securityContextImpl.getAuthentication().getPrincipal();
        }
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("schoolId", (long)1);
            paramMap.put("goodsIdentifying", 2);
            paramMap.put("currentPage", 0);
            paramMap.put("pageSize", 5);
            list = goodsService.getUsedGoodsList(paramMap);
            if(list.size() > 0) {
            	for(int i = 0;i < list.size(); i++) {
            		Map<String, Object> m = new HashMap<String,Object>();
            		m = list.get(i);
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("goodsId", m.get("goodsId"));
            		m.put("leaveMessageCount", leaveMessageService.getGoodsLeaveMessage(params).size());
            		//查询我是否收藏了此商品
            		if(ObjUtil.isNotNullAndEmpty(ud)) {
            			params.put("userId", ud.getUserId());
            			params.put("targetId", m.get("goodsId"));
            			params.put("attentionType", (byte)1);
            			List<Map<String, Object>> favoritesdList = favoritesService.getFavoritesList(params);
            			if(favoritesdList.size() > 0) {
            				m.put("isFavoritesd", 1);
            			}else {
            				m.put("isFavoritesd", 0);
            			}
            		}else {
            			m.put("isFavoritesd", 0);
            		}
            		list2.add(m);
            	}
            }
            req.setAttribute("usedGoodsList", list2);//二手商品
            
            paramMap.put("pageSize", 6);
            paramMap.put("goodsIdentifying", 3);
            buyGoodsList = goodsService.getUsedGoodsList(paramMap);
            if(buyGoodsList.size() > 0) {
            	for(int i = 0;i < buyGoodsList.size(); i++) {
            		Map<String, Object> m = new HashMap<String,Object>();
            		m = buyGoodsList.get(i);
                    Map<String, Object> params = new HashMap<String, Object>();
                    params.put("goodsId", m.get("goodsId"));
            		m.put("leaveMessageCount", leaveMessageService.getGoodsLeaveMessage(params).size());
            		//查询我是否收藏了此商品
            		if(ObjUtil.isNotNullAndEmpty(ud)) {
            			params.put("userId", ud.getUserId());
            			params.put("targetId", m.get("goodsId"));
            			params.put("attentionType", (byte)1);
            			List<Map<String, Object>> favoritesdList = favoritesService.getFavoritesList(params);
            			if(favoritesdList.size() > 0) {
            				m.put("isFavoritesd", 1);
            			}else {
            				m.put("isFavoritesd", 0);
            			}
            		}else {
            			m.put("isFavoritesd", 0);
            		}
            		buyGoodsList2.add(m);
            	}
            }
            
            req.setAttribute("buyGoodsList", buyGoodsList2);//求购商品
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return "app/usedGoodsList";
    }

    /**
     * 获取我发布的二手商品列表
     * @param req
     * @return
     */
    @RequestMapping("app/getUserUsedGoodsList")
    public String getUserUsedGoodsList(HttpServletRequest req){
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        //获取登录人用户信息
        MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("userId", ud.getUserId());
            list = goodsService.getUsedGoodsList(paramMap);
            req.setAttribute("usedGoodsList", list);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return "app/usedGoodsList";
    }
    /**
     * 二手商品擦亮
     * @param req
     * @return
     */
    @RequestMapping("app/goodsPolish")
    @ResponseBody
    public Map<String, Object> goodsPolish(HttpServletRequest req){
        Map<String, Object> map = new HashMap<String, Object>();
        String goodsId = req.getParameter("goodsId");
        try {
            Goods goods = new Goods();
            goods.setGoodsId(Long.parseLong(goodsId));
            goods.setUpdateDate(new Date());
            goodsService.updateByPrimaryKeySelective(goods);
            map.put("state", 1);
            map.put("msg", "擦亮成功");
        } catch (Exception e) {
            map.put("state", 1);
            map.put("msg", "擦亮失败");
            e.printStackTrace();
            logger.error(e);
        }
        return map;
    }

//    /**
//     * 通过二手商品Id获取二手商品信息
//     * @param req
//     * @return
//     */
//    @RequestMapping("app/getUsedGoodsInfo")
//    public String getUsedGoodsInfo(HttpServletRequest req){
//        MyUserDetail ud = null;
//        SecurityContextImpl securityContextImpl = (SecurityContextImpl)req.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
//        if(ObjUtil.isNotNullAndEmpty(securityContextImpl)) {
//        	ud = (MyUserDetail) securityContextImpl.getAuthentication().getPrincipal();
//        }
//        Map<String, Object> map = new HashMap<String, Object>();
//        String goodsId = req.getParameter("goodsId");
//        try {
//            Map<String, Object> paramMap = new HashMap<String, Object>();
//            paramMap.put("goodsId", goodsId);
//            map = goodsService.getUsedGoodsInfo(paramMap);
//            req.setAttribute("usedGoodsInfo", map);
//            //获取回复列表
//            List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
//            List<Map<String,Object>> goodsLeaveMessage = leaveMessageService.getGoodsLeaveMessage(paramMap);
//            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            for(int i =0;i<goodsLeaveMessage.size();i++) {
//                Map<String, Object> m = new HashMap<String, Object>();
//                List<Map<String,Object>> hfListMap = new ArrayList<Map<String,Object>>();
//                m =  goodsLeaveMessage.get(i);
//                Date dateCreateDate = simpleDateFormat.parse(goodsLeaveMessage.get(i).get("createDate").toString());
//                //获取时间中文
//                m.put("timeStr", getTimeStr(dateCreateDate));
//                Long receiverId=(Long) goodsLeaveMessage.get(i).get("leaveMessageId");
//                for(;;) {
//                	Map<String, Object> params = new HashMap<String, Object>();
//               	 	params.put("receiverId", receiverId);
//                    Map<String, Object> replyLeaveMessage = leaveMessageService.getReplyLeaveMessage(params); 
//                    if(replyLeaveMessage != null) {
//                    	Map<String, Object> m1 = new HashMap<String, Object>();
//                    	Date dateCreateDate1 = simpleDateFormat.parse(replyLeaveMessage.get("createDate").toString());
//                        m1.put("timeHuiFuStr", getTimeStr(dateCreateDate1));
//                        m1.put("replyLeaveMessage", replyLeaveMessage);
//                        hfListMap.add(m1);
//                        receiverId=(Long) replyLeaveMessage.get("leaveMessageId");
//                    }else {
//                    	m.put("huiFu", hfListMap);
//                    	hfListMap = new ArrayList<Map<String,Object>>();
//                    	break;
//                    }
//                }
//                listMap.add(i, m);
//            }
//            req.setAttribute("leaveMessageList",listMap );
//            req.setAttribute("usersInfo", ud);
//            Favorites favorites = new Favorites();
//            favorites.setTargetId(Long.parseLong(goodsId));
//            if(ObjUtil.isNotNullAndEmpty(ud)) {
//                favorites.setUserId(ud.getUserId());
//            }
//            Favorites favoritesInfo = favoritesService.getFavoritesByTargetIdAndFavoriteType(favorites);
//            req.setAttribute("favoritesInfo", favoritesInfo);
//            Goods goods = new Goods();
//            goods.setGoodsId(Long.parseLong(goodsId));
//            int pageView = Integer.parseInt(map.get("pageView").toString());
//            goods.setPageView(pageView+1);
//            goodsService.updateByPrimaryKeySelective(goods);
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(e);
//        }
//        return "app/usedGoods";
//    }
    
    /**
     * 通过二手商品Id获取二手商品信息
     * @param req
     * @return
     */
    @RequestMapping("app/getUsedGoodsInfo")
    public String getUsedGoodsInfo(HttpServletRequest req){
    	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        MyUserDetail ud = null;
        SecurityContextImpl securityContextImpl = (SecurityContextImpl)req.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        if(ObjUtil.isNotNullAndEmpty(securityContextImpl)) {
        	ud = (MyUserDetail) securityContextImpl.getAuthentication().getPrincipal();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        String goodsId = req.getParameter("goodsId");
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("goodsId", goodsId);
            map = goodsService.getUsedGoodsInfo(paramMap);
            req.setAttribute("usedGoodsInfo", map);//商品信息
            
            //所有的商品留言
            List<Map<String,Object>> goodsLeaveMessage = leaveMessageService.getGoodsLeaveMessage(paramMap);
            
            //获取留言的回复
            List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
            
            for(int i =0;i<goodsLeaveMessage.size();i++) {
                
                
                //留言人信息
                Map<String, Object> m = goodsLeaveMessage.get(i);
                
                Date dateCreateDate = simpleDateFormat.parse(goodsLeaveMessage.get(i).get("createDate").toString());
                //获取时间中文
                m.put("timeStr", DateUtils.getTimeStr(dateCreateDate));
                
                //留言人标识
                Long identifying=(Long) m.get("leaveMessageId");
                
            	Map<String, Object> params = new HashMap<String, Object>();
           	 	params.put("identifying", identifying);
           	 	
           	 	//留言人回复人列表
                List<Map<String, Object>> replyLeaveMessage = leaveMessageService.getReplyLeaveMessage(params); 
                List<Map<String, Object>> replyLeaveMessage2 = new ArrayList<Map<String,Object>>(); 
                
                if(replyLeaveMessage.size() > 0) {
                	for(int j = 0;j < replyLeaveMessage.size(); j++) {
                		Map<String, Object> m1 = replyLeaveMessage.get(j);
                		Date dateCreateDate1 = simpleDateFormat.parse(replyLeaveMessage.get(j).get("createDate").toString());
                		m1.put("timeHuiFuStr", DateUtils.getTimeStr(dateCreateDate1));
                		replyLeaveMessage2.add(m1);
                	}
                }
                m.put("replyLeaveMessage", replyLeaveMessage2);
                listMap.add(i, m);
            }
            req.setAttribute("leaveMessageList",listMap);
            req.setAttribute("usersInfo", ud);
            Favorites favorites = new Favorites();
            favorites.setTargetId(Long.parseLong(goodsId));
            if(ObjUtil.isNotNullAndEmpty(ud)) {
                favorites.setUserId(ud.getUserId());
            }
            Favorites favoritesInfo = favoritesService.getFavoritesByTargetIdAndFavoriteType(favorites);
            req.setAttribute("favoritesInfo", favoritesInfo);
            Goods goods = new Goods();
            goods.setGoodsId(Long.parseLong(goodsId));
            int pageView = Integer.parseInt(map.get("pageView").toString());
            goods.setPageView(pageView+1);
            goodsService.updateByPrimaryKeySelective(goods);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return "app/usedGoods";
    }
    /**
     * 通过求购商品Id获取求购商品信息
     * @param req
     * @return
     */
    @RequestMapping("app/getWantBuyDetail")
    public String getWantBuyDetail(HttpServletRequest req){
    	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        MyUserDetail ud = null;
        SecurityContextImpl securityContextImpl = (SecurityContextImpl)req.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        if(ObjUtil.isNotNullAndEmpty(securityContextImpl)) {
        	ud = (MyUserDetail) securityContextImpl.getAuthentication().getPrincipal();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        String goodsId = req.getParameter("goodsId");
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("goodsId", goodsId);
            map = goodsService.getUsedGoodsInfo(paramMap);
            req.setAttribute("usedGoodsInfo", map);//商品信息
            
            //所有的商品留言
            List<Map<String,Object>> goodsLeaveMessage = leaveMessageService.getGoodsLeaveMessage(paramMap);
            
            //获取留言的回复
            List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
            
            for(int i =0;i<goodsLeaveMessage.size();i++) {
                
                
                //留言人信息
                Map<String, Object> m = goodsLeaveMessage.get(i);
                
                Date dateCreateDate = simpleDateFormat.parse(goodsLeaveMessage.get(i).get("createDate").toString());
                //获取时间中文
                m.put("timeStr", DateUtils.getTimeStr(dateCreateDate));
                
                //留言人标识
                Long identifying=(Long) m.get("leaveMessageId");
                
            	Map<String, Object> params = new HashMap<String, Object>();
           	 	params.put("identifying", identifying);
           	 	
           	 	//留言人回复人列表
                List<Map<String, Object>> replyLeaveMessage = leaveMessageService.getReplyLeaveMessage(params); 
                List<Map<String, Object>> replyLeaveMessage2 = new ArrayList<Map<String,Object>>(); 
                
                if(replyLeaveMessage.size() > 0) {
                	for(int j = 0;j < replyLeaveMessage.size(); j++) {
                		Map<String, Object> m1 = replyLeaveMessage.get(j);
                		Date dateCreateDate1 = simpleDateFormat.parse(replyLeaveMessage.get(j).get("createDate").toString());
                		m1.put("timeHuiFuStr", DateUtils.getTimeStr(dateCreateDate1));
                		replyLeaveMessage2.add(m1);
                	}
                }
                m.put("replyLeaveMessage", replyLeaveMessage2);
                listMap.add(i, m);
            }
            req.setAttribute("leaveMessageList",listMap);
            req.setAttribute("usersInfo", ud);
            Favorites favorites = new Favorites();
            favorites.setTargetId(Long.parseLong(goodsId));
            if(ObjUtil.isNotNullAndEmpty(ud)) {
                favorites.setUserId(ud.getUserId());
            }
            Favorites favoritesInfo = favoritesService.getFavoritesByTargetIdAndFavoriteType(favorites);
            req.setAttribute("favoritesInfo", favoritesInfo);
            Goods goods = new Goods();
            goods.setGoodsId(Long.parseLong(goodsId));
            int pageView = Integer.parseInt(map.get("pageView").toString());
            goods.setPageView(pageView+1);
            goodsService.updateByPrimaryKeySelective(goods);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return "app/wantBuyDetail";
    }

    /**
     * @Title: toTwoHandPushList
     * @Description: TODO(跳转我的发布页面)
     * @param @param req
     * @param @return
     * @return String    返回类型
     * @throws
     */
    @RequestMapping("app/toTwoHandPushList")
    public String toTwoHandPushList(HttpServletRequest req){
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> buyList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> buyList2 = new ArrayList<Map<String, Object>>();
        //获取登录人用户信息
        MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            Map<String, Object> paramMap2 = new HashMap<String, Object>();
            paramMap.put("userId", ud.getUserId());
            paramMap.put("goodsIdentifying", 2);
            list = goodsService.getAllUsedGoodsList(paramMap);
            for(int i=0;i<list.size();i++){
                Map<String, Object> m = list.get(i);
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("goodsId", m.get("goodsId"));
                m.put("leaveMessageCount", leaveMessageService.getGoodsLeaveMessage(params).size());
                list2.add(m);
            }
            req.setAttribute("usedGoodsList", list2);
            
            paramMap2.put("goodsIdentifying", 3);
            paramMap2.put("userId", ud.getUserId());
            buyList = goodsService.getAllUsedGoodsList(paramMap2);
            for(int i=0;i<buyList.size();i++){
                Map<String, Object> m1 = buyList.get(i);
                Map<String, Object> params1 = new HashMap<String, Object>();
                params1.put("goodsId", m1.get("goodsId"));
                m1.put("leaveMessageCount", leaveMessageService.getGoodsLeaveMessage(params1).size());
                buyList2.add(m1);
            }
            req.setAttribute("buyList", buyList2);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return "app/twoHandPushList";
    }


    /**
     * 根据商品类型获取所有商品信息列表
     * @param req goodsName(商品名) merchantId(商家ID)
     * @return
     */
    @RequestMapping("app/goodsByClassifyList")
    @ResponseBody
    public List<Map<String,Object>> goodsByClassifyList(HttpServletRequest req){
        String goodsName = req.getParameter("goodsName");
        String classifyId1 = req.getParameter("classifyId1");
    	String currentPage = req.getParameter("currentPage");
		String pageSize = req.getParameter("pageSize");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        //获取登录人用户信息
//		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("goodsName", goodsName);
//            paramMap.put("schoolId", ud.getSchoolId());
            paramMap.put("schoolId", (long)1);
            paramMap.put("classifyId1", Long.parseLong(classifyId1));
            paramMap.put("currentPage", (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize));
            paramMap.put("pageSize", pageSize);
            list = goodsService.goodsByClassifyList(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return list;
    }

    /**
     * 获取零食小吃的商品列表
     * @param req goodsName(商品名) merchantId(商家ID)
     * @return
     */
    @RequestMapping("app/getGoodsListBySnacks")
    public String getGoodsListBySnacks(HttpServletRequest req){
        String goodsName = req.getParameter("goodsName");
        String classifyId1 = req.getParameter("classifyId1");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            paramMap.put("goodsName", goodsName);
//            paramMap.put("schoolId", ud.getSchoolId());
            paramMap.put("schoolId", (long)1);
            paramMap.put("classifyId1", Long.parseLong(classifyId1));
            list = goodsService.goodsByClassifyList(paramMap);
            req.setAttribute("goodsList", list);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }
        return "app/snacks";
    }
    
}
